package com.xbj.controller;

import com.github.pagehelper.PageInfo;
import com.xbj.annotation.RequirePermission;
import com.xbj.domain.*;
import com.xbj.service.EmpService;
import com.xbj.service.UserService;
import com.xbj.util.*;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/emp/")
public class EmpController {
    protected Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private EmpService empService;
    @Autowired
    private UserService userService;

    @RequirePermission("emp:zixun")
    @RequestMapping("listUI")
    public String listUI(Model model, @RequestParam(name = "opr", required = false) String opr) throws Exception {
        List<Map<String, Object>> userMap = empService.findUser();
        System.out.println("opr=====" + opr);

        if ("todayHf".equals(opr)) {// 今日需回访
            model.addAttribute("zx_opr", opr);
        } else if ("notHf".equals(opr)) {
            model.addAttribute("zx_opr", opr);// 不在回访
        } else if ("today_zx".equals(opr)) {
            model.addAttribute("zx_opr", opr);// 今日需咨询
        } else if ("waitHf".equals(opr)) {
            model.addAttribute("zx_opr", opr);// 今日需咨询
        } else if ("historyzx".equals(opr)) {
            model.addAttribute("zx_opr", opr);// 历史已咨询
        } else {
            model.addAttribute("zx_opr", opr);
        }
        // 查询咨询师
        model.addAttribute("userMap", userMap);

        return "emp/listUI";
    }

    /**
     * 电销记录列表查询
     *
     * @param model
     * @return
     * @throws Exception
     */
    @RequirePermission("emp:zixun")
    @RequestMapping("listUI_dx")
    public String listUI_DX(Model model, HttpServletRequest request) throws Exception {
        String operate = request.getParameter("opr");
        System.out.println("======operate=====" + operate);
        List<Map<String, Object>> userMap = empService.findUser();
        model.addAttribute("userMap", userMap);

        List<Map<String, Object>> dxUserMap = empService.findDxUser();
        model.addAttribute("dxUserMap", dxUserMap);

        model.addAttribute("operate", operate);
        return "emp/listUI_dx";
    }

    @RequirePermission("emp:zixun")
    @RequestMapping("toAddEmp")
    public String toaddEmp() {
        return "emp/addEmp";
    }

    /*
     * @RequirePermission("user:listUI")
     *
     * @RequestMapping("getEmpListBySeacher")
     *
     * @ResponseBody public Result getEmpListBySeacher(@RequestParam(value =
     * "userid", required = false) Integer userid) { // 查询用户列表信息 List<Emp> empList =
     * empService.findEmpList(userid); return Result.succeed(empList); }
     */

    /**
     * 下载模板
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/downExcel")
    public void downExcel(HttpServletResponse response) throws Exception {
        FileDownload.fileDownload(response, PathUtil.getClasspath() + Common.FILEPATHFILE + "Emps.xls", "Emps.xls");
    }

    /**
     * 从EXCEL导入到数据库
     */
    @ResponseBody
    @RequestMapping(value = "/uploadExcel")
    public Result readExcel(@RequestParam(value = "excelFile", required = false) MultipartFile file) throws Exception {
        PageData pd = new PageData();

        if (null != file && !file.isEmpty()) {
            String filePath = PathUtil.getClasspath() + Common.FILEPATHFILE; // 文件上传路径
            String fileName = FileUpload.fileUp(file, filePath, "empexcel"); // 执行上传

            // 执行读EXCEL操作,读出的数据导入List；
            // 2:从第3行开始；0:从第A列开始；0:第0个sheet
            @SuppressWarnings({"unchecked", "rawtypes"})
            List<PageData> listPd = (List) ObjectExcelRead.readExcel(filePath, fileName, 2, 0, 0);
            /**
             * var0 :姓名 var1 :性别 var2 :电话 var3 :QQ var4 :应聘岗位 var5 :学历 var6 :专业 var7 :学校
             * var8 :年龄 var9 :毕业时间 var10 :状态
             */
            if (listPd != null && listPd.size() > 0) {
                for (int i = 0; i < listPd.size(); i++) {
                    pd.put("empName", listPd.get(i).getString("var0")); // 姓名
                    pd.put("gender", listPd.get(i).getString("var1")); // 性别
                    pd.put("phone", listPd.get(i).getString("var2")); // 电话
                    pd.put("QQ", listPd.get(i).getString("var3")); // QQ
                    pd.put("empPosition", listPd.get(i).getString("var4")); // 应聘岗位
                    pd.put("education", listPd.get(i).getString("var5")); // 学历
                    pd.put("major", listPd.get(i).getString("var6")); // 专业
                    pd.put("school", listPd.get(i).getString("var7")); // 学校
                    pd.put("birthday", listPd.get(i).getString("var8")); // 年龄
                    pd.put("source", listPd.get(i).getString("var9")); // 数据来源
                    pd.put("graduateDate", listPd.get(i).getString("var10")); // 毕业时间
                    pd.put("empStatus", listPd.get(i).getString("var11")); // 状态
                    /* 存入数据库操作====================================== */
                }
            } else {
                return Result.fail();
            }
        } else {
            return Result.fail(404, "文件为空");
        }
        return Result.fail();
    }

    @RequestMapping("findNameById/{userId}")
    @ResponseBody
    public Result findNameById(@PathVariable(name = "userId", required = false) Integer userId) {
        System.out.println("userId====" + userId);
        String nameById = userService.findNameById(userId);
        return Result.succeed(nameById);
    }

    /**************************************
     * 保存学员信息
     ********************************************/

    @RequestMapping("addEmp")
    @ResponseBody
    public Result addEmp(Emp emp, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("loginUser");
        Integer userid = user.getId();
        EmpDxDesc empdxdesc = new EmpDxDesc();
        // 设置电销人的ID为当前登录人的ID
        empdxdesc.setDxId(userid);
        // 电销日期就是导入的日期
        empdxdesc.setDxDate(new Date());
        emp.setEmpdxdesc(empdxdesc);
        emp.setEmpState("1");
        this.empService.addEmp(emp);
        return Result.succeed("新增成功");
    }

    /**************************************
     * 电销查询列表
     ********************************************/
    /**
     * 根据登录用户查询电销列表中的内容 根据条件查询列表
     *
     * @throws ParseException
     */
    @RequirePermission("emp:dx")
    @RequestMapping("listDx")
    @ResponseBody
    public Result listDx(int offset, int limit, String search,
                         @RequestParam(name = "empName", required = false) String empName,
                         @RequestParam(name = "phone", required = false) String phone,
                         @RequestParam(name = "school", required = false) String school,
                         @RequestParam(name = "major", required = false) String major,
                         @RequestParam(name = "dxDate", required = false) String dxDate,
                         @RequestParam(name = "operate", required = false) String operate, HttpServletRequest request) {
        User u = (User) request.getSession().getAttribute("loginUser");
        Integer userid = u.getId();
        Emp emp = new Emp();
        emp.setEmpName(empName);
        emp.setPhone(phone);
        // emp.setEmpQQ(empQQ);
        emp.setSchool(school);
        emp.setMajor(major);
        EmpDxDesc empdxdesc = new EmpDxDesc();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        // now表示今日需电销todayHf表示今日需回访
        if ("now".equals(operate) || "todayHf".equals(operate)) {
            date = new Date();
            String string = sdf.format(date);
            try {
                date = sdf.parse(string);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        try {
            if (dxDate != null && dxDate != "") {
                date = sdf.parse(dxDate);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if ("dx".equals(operate)) {
            empdxdesc.setDxId(null);
        } else {
            empdxdesc.setDxId(userid);
        }
        empdxdesc.setDxDate(date);
        if ("todayHf".equals(operate)) {
            empdxdesc.setHfDate(date);
            empdxdesc.setHfStatus("0");
        }
        // 不需要回访的信息直接传递过去一个回访的状态值
        if ("notHf".equals(operate)) {
            empdxdesc.setHfStatus("1");
        }
        // 判断是待回访信息
        if ("waitHf".equals(operate)) {
            // 将DxDate置空并且设置回访日期
            // 在上面得到的dxDate实际上是回访信息中的查询的日期
            empdxdesc.setDxDate(null);
            empdxdesc.setHfDate(date);
            empdxdesc.setHfStatus("0");
        }
        empdxdesc.setOperate(operate);
        emp.setEmpdxdesc(empdxdesc);

        // 查询用户列表信息
        PageInfo<Emp> pageInfo = this.empService.getListByDX(offset / limit + 1, limit, emp);
        return Result.succeed(pageInfo);
    }

    /**************************************
     * 根据ID获取当前电销备注信息
     ********************************************/
    @RequestMapping("getEmpDesc/{id}")
    @ResponseBody
    public Result getEmpDesc(@PathVariable(name = "id", required = false) Integer id) {
        System.out.println("id======" + id);
        Map<String, Object> map = empService.getEmpDesc(id);
        return Result.succeed(map);
    }

    /**************************************
     * 保存电销备注信息
     ********************************************/
    @RequestMapping("savedxdesc")
    @ResponseBody
    public Result savedesc(@RequestParam(name = "empId", required = false) Integer empId,
                           @RequestParam(name = "dxDesc", required = false) String desc,
                           @RequestParam(name = "descId", required = false) Integer descId,
                           @RequestParam(name = "hfStatus", required = false) String hfStatus,
                           @RequestParam(name = "hfDate", required = false) String hfDate) {
        // empId=&descId=&dxDesc=sasaas&hfDate=2019-01-22&hfStatus=0
        System.out.println("empId====" + empId);
        System.out.println("desc====" + desc);
        System.out.println("descId====" + descId);
        System.out.println("hfStatus====" + hfStatus);
        System.out.println("hfDate====" + hfDate);
        EmpDxDesc edx = new EmpDxDesc();
        edx.setId(descId);
        edx.setDxDesc(desc);
        edx.setHfStatus(hfStatus);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            if (hfDate != null && hfDate != "") {
                date = sdf.parse(hfDate);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        edx.setHfDate(date);
        int i = empService.saveDxDesc(edx);
        if (i == 0) {
            return Result.fail();
        }
        // 判断是否需要回访，不需要的时候修改emp中empStatus状态为D
        // 0表示需要回访1表示不需要回访
        if ("1".equals(hfStatus)) {
            empService.updateEmpStatus(empId);
        }

        return Result.succeed("success", i);
    }

    /**************************************
     * 电销转咨询内容
     ********************************************/
    @RequestMapping("savezxRecord")
    @ResponseBody
    public Result savezxRecord(@RequestParam(name = "zxdescid", required = false) Integer zxdescid,
                               @RequestParam(name = "empId", required = false) Integer empId,
                               @RequestParam(name = "zxDate", required = false) String zxDate,
                               @RequestParam(name = "zxId", required = false) String zxId) {
        System.out.println("empId====" + empId);
        int i = 0;
        if (zxdescid == null) {
            i = empService.saveDxToZxRecord(empId, zxDate, zxId);
        } else {
            i = empService.updateDxToZxRecord(zxdescid, empId, zxDate, zxId);
        }
        if (i == 0) {
            return Result.fail();
        } else {
            // 转咨询之后修改学员的转咨询状态
            empService.updateEmpState(empId);
        }
        return Result.succeed("success", i);
    }

    @RequestMapping("savedxRecord")
    @ResponseBody
    public Result savedxRecord(@RequestParam(name = "empId", required = true) Integer empId,
                               @DateTimeFormat(pattern = "yyyy-MM-dd")
                               @RequestParam(name = "dxDate", required = true) Date dxDate,
                               @RequestParam(name = "dxId", required = true) Integer dxId) {
        System.out.println("empId====" + empId);
        int i = 0;
        i = empService.updateDxToDxRecord(empId, dxId, dxDate);
        if (i == 0) {
            return Result.fail();
        } else {
            // 转咨询之后修改学员的转咨询状态
            empService.updateEmpState(empId);
        }
        return Result.succeed("success", i);
    }


    /**************************************
     * 根据学员ID查询zx内容
     ********************************************/
    @RequestMapping("findZxRecord/{empid}")
    @ResponseBody
    public Result findZxRecord(@PathVariable(name = "empid", required = false) Integer empid) {
        System.out.println("empid====" + empid);
        EmpZxDesc zxrecord = empService.findZxRecord(empid);
        return Result.succeed(zxrecord);
    }

    /**************************************
     * 咨询查询列表
     *
     * @throws ParseException
     ***********************************/
    @RequirePermission("emp:zixun")
    @RequestMapping("listZx")
    @ResponseBody
    public Result listZx(int offset, int limit, String search,
                         @RequestParam(name = "empName", required = false) String empName,
                         @RequestParam(name = "zxId", required = false) Integer zxId,
                         @RequestParam(name = "phone", required = false) String phone,
                         @RequestParam(name = "school", required = false) String school,
                         @RequestParam(name = "major", required = false) String major,
                         @RequestParam(name = "zxDate", required = false) String zxDate,
                         @RequestParam(name = "opr", required = false) String operate, HttpServletRequest request)
            throws ParseException {

        User u = (User) request.getSession().getAttribute("loginUser");
        Emp emp = new Emp();
        emp.setEmpName(empName);
        emp.setPhone(phone);
        // emp.setEmpQQ(empQQ);
        emp.setSchool(school);
        emp.setMajor(major);
        EmpZxDesc ezd = new EmpZxDesc();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if ("historyzx".equals(operate)) {
            if (zxDate != null && zxDate != "") {
                ezd.setZxstatus1Date(sdf.parse(zxDate));
            } else {
                ezd.setZxstatus1Date(sdf.parse(sdf.format(new Date())));
            }
        } else {
            if (zxDate != null && zxDate != "") {
                ezd.setZxDate(sdf.parse(zxDate));
            }
        }

        if (zxId == null) {
            Integer userid = u.getId();
            // 判断是否为最高权限，如果为最高权限则不设置zxid
            boolean result = empService.findEmpPermissionById(userid);
            if (result) {
                ezd.setZxId(null);
                emp.setEmpState("2");
            } else {
                ezd.setZxId(userid);
            }
        } else {
            ezd.setZxId(zxId);
        }
        // 判断为今日咨询将咨询时间设置成当天
        if ("today_zx".equals(operate)) {
            String today = sdf.format(new Date());
            ezd.setZxDate(sdf.parse(today));
        } else if ("todayHf".equals(operate)) {// 判断操作为今日回访,设置回访日期为今日，并且回访状态为0
            String today = sdf.format(new Date());
            ezd.setHfDate(sdf.parse(today));
            ezd.setHfStatus("0");
        } else if ("notHf".equals(operate)) {// 不需要回访的信息直接传递过去一个回访的状态值
            ezd.setHfStatus("1");
        } else if ("waitHf".equals(operate)) {// 待回访信息
            ezd.setHfStatus("0");
        }
        ezd.setOperate(operate);
        emp.setEmpzxdesc(ezd);

        // 查询用户列表信息
        PageInfo<Emp> pageInfo = this.empService.getListByZX(offset / limit + 1, limit, emp);
        return Result.succeed(pageInfo);
    }

    /**************************************
     * 根据ID获取当前咨询备注信息
     ********************************************/
    @RequestMapping("getEmpDescByZx/{id}")
    @ResponseBody
    public Result getEmpDescByZx(@PathVariable(name = "id", required = false) Integer id) {
        System.out.println("id======" + id);
        Map<String, Object> map = empService.getEmpDescByZx(id);
        return Result.succeed(map);
    }

    /**************************************
     * 保存咨询备注信息
     *
     * @throws ParseException
     ********************************************/
    @RequestMapping("savezxdesc")
    @ResponseBody
    public Result savezxdesc(@RequestParam(name = "empId", required = false) Integer empId,
                             @RequestParam(name = "zxDesc", required = false) String desc,
                             @RequestParam(name = "descId", required = false) Integer descId,
                             @RequestParam(name = "hfStatus", required = false) String hfStatus,
                             @RequestParam(name = "hfDate", required = false) String hfDate) throws ParseException {
        EmpZxDesc edx = new EmpZxDesc();
        edx.setId(descId);
        edx.setZxDesc(desc);
        edx.setHfStatus(hfStatus);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            if (hfDate != null && hfDate != "") {
                date = sdf.parse(hfDate);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        edx.setHfDate(date);
        edx.setZxstatus1Date(sdf.parse(sdf.format(new Date())));
        int i = empService.saveZxDesc(edx);
        // 判断是否需要回访，不需要的时候修改emp中empStatus状态为D
        // 0表示需要回访1表示不需要回访
        if ("1".equals(hfStatus)) {
            empService.updateEmpStatus(empId);
        }
        if (i == 0) {
            return Result.fail();
        }
        return Result.succeed("success", i);
    }

    /**************************************
     * 保存学员信息
     ********************************************/

    @RequestMapping("updateEmp")
    @ResponseBody
    public Result updateEmp(@RequestParam(value = "empId") Integer empId, @RequestParam(value = "field") String field,
                            @RequestParam(value = "newValue") String newValue, HttpServletRequest request) {
        System.out.println("field==" + field);
        System.out.println("empId==" + empId);
        System.out.println("newValue==" + newValue);
        this.empService.updateEmp(empId, field, newValue);
        return Result.succeed("新增成功");
    }

    /*
     * 导出学员信息到EXCEL
     *
     * @return
     */
    @RequestMapping(value = "/excel")
    public ModelAndView exportExcel(@RequestParam(required = false, value = "ids") String ids,
                                    HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        System.out.println("ids=====" + ids);
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();

            titles.add("ID"); // 1
            titles.add("学员名称"); // 2
            titles.add("电话"); // 3
            titles.add("QQ号码"); // 4
            titles.add("应聘岗位"); // 5
            titles.add("学历"); // 6
            titles.add("专业"); // 7
            titles.add("学校"); // 8
            titles.add("年龄"); // 9
            titles.add("毕业时间"); // 10
            titles.add("数据来源"); // 11
            titles.add("电销人员"); // 12
            titles.add("状态"); // 13
            titles.add("电销备注"); // 14
            titles.add("咨询备注"); // 15
            dataMap.put("titles", titles);

            List<Integer> listids = new ArrayList<>();
            String[] idss = ids.split(",");
            for (int i = 0; i < idss.length; i++) {
                Integer id = Integer.valueOf(idss[i]);
                listids.add(id);
            }
            // 根据选中的ids查询需要导出的数据信息
            List<Emp> excel = empService.findEmpExcel(listids);
            System.out.println("excel=====" + excel);
            ObjectExcelView erv = new ObjectExcelView(); // 执行excel操作

            List<PageData> varList = new ArrayList<PageData>();
            for (int i = 0; i < excel.size(); i++) {
                PageData vpd = new PageData();
                Emp emp = excel.get(i);
                vpd.put("var1", String.valueOf(emp.getId())); // 1
                vpd.put("var2", emp.getEmpName()); // 2
                vpd.put("var3", emp.getPhone()); // 3
                vpd.put("var4", emp.getEmpQQ()); // 4
                vpd.put("var5", emp.getEmpPosition()); // 5
                vpd.put("var6", emp.getEducation()); // 6
                vpd.put("var7", emp.getMajor()); // 7
                vpd.put("var8", emp.getSchool()); // 8
                vpd.put("var9", emp.getBirthday()); // 9
                vpd.put("var10", emp.getGraduateDate()); // 10
                vpd.put("var11", emp.getSource()); // 11
                vpd.put("var12", emp.getDxUserId()); // 12
                vpd.put("var13", emp.getEmpStatus()); // 13
                vpd.put("var14", emp.getEmpdxdesc() == null ? "" : emp.getEmpdxdesc().getDxDesc()); // 14
                vpd.put("var15", emp.getEmpzxdesc() == null ? "" : emp.getEmpzxdesc().getZxDesc()); // 15
                varList.add(vpd);
            }
            dataMap.put("varList", varList);
            ObjectExcelView erv1 = new ObjectExcelView(); // 执行excel操作
            mv = new ModelAndView(erv1, dataMap);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    @RequestMapping("findUserByLoginId")
    @ResponseBody
    public boolean findUserByLoginId(HttpServletRequest request) {
        User u = (User) request.getSession().getAttribute("loginUser");
        Integer userid = u.getId();
        // 判断是否为最高权限，如果为最高权限则不设置zxid
        boolean result = empService.findEmpPermissionById(userid);
        return result;
    }

    /**
     * 根据选择已报名保存已报名信息
     *
     * @param empDetail
     * @param request
     * @return
     * @throws ParseException
     */
    @RequestMapping("saveEmpDetail")
    @ResponseBody
    public Result saveEmpDetail(@Param(value = "empId") Integer empId, @Param(value = "field") String field,
                                @Param(value = "newValue") String newValue, @Param(value = "empDetail") EmpDetail empDetail,
                                HttpServletRequest request) throws ParseException {
        System.out.println("empDetail=====" + empDetail);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String format = sdf.format(new Date());
        empDetail.setApplyDate(sdf.parse(format));
        EmpDetail detail = empService.findEmpDetailByEmpId(empId);
        int result = 0;
        if (detail != null) {
            result = empService.updateEmpDetail(empDetail);
        } else {
            result = empService.saveEmpDetail(empDetail);
        }
        System.out.println("result=====" + result);
        if (result == 1) {
            this.empService.updateEmp(empId, field, newValue);
            return Result.succeed("success", result);
        }
        return Result.fail();
    }

    @RequestMapping("listUI_month")
    public String listUIMonth(Model model, @RequestParam(name = "opr", required = false) String opr) throws Exception {
        List<Map<String, Object>> userMap = empService.findUser();
        // 查询咨询师
        model.addAttribute("userMap", userMap);
        return "emp/listUI_month";
    }

    @RequestMapping("listZx_Month")
    @ResponseBody
    public Result listZx_Month(int offset, int limit, @RequestParam(name = "zxId", required = false) Integer zxId,
                               @RequestParam(name = "applyDate", required = false) String applyDate, HttpServletRequest request)
            throws ParseException {

        User u = (User) request.getSession().getAttribute("loginUser");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Map<String, Object> map = new HashMap<>();
        Integer userid = u.getId();
        if (zxId == null) {
            // 判断是否为最高权限，如果为最高权限则不设置zxid
            boolean result = empService.findEmpPermissionById(userid);
            if (result) {
                map.put("zxid", null);
            } else {
                map.put("zxid", userid);
            }
        } else {
            map.put("zxid", zxId);
        }
        map.put("applyDate", applyDate);
        // 查询用户列表信息
        PageInfo<Emp> pageInfo = this.empService.findEmpByDetailApplyDate(offset / limit + 1, limit, map);
        return Result.succeed(pageInfo);
    }

}
